<template>
    <div class="search-set">
        <el-input v-model="searchKey" :placeholder="$t('chat-txt.search-txt')" suffix-icon="Search" @click="props.openChatSearch" />
        <el-icon size="16" color="#4c4c4c" @click="props.openMsgSet"><Setting /></el-icon>
        <div class="address-book" style="height: 20px;">
            <!-- <div class="cursor" @click="props.openAddressBook">
                <el-icon size="16" color="#4c4c4c"><UserFilled /></el-icon>
                <span>通讯录</span>
            </div> -->
        </div>
    </div>
    <div class="collapse-box">
        <el-collapse v-model="msgCollapse">
            <el-collapse-item :title="`${$t('chat-txt.txt-1')} (${tempDataList.length})`" name="1">
                <div class="user-list" v-if="tempDataList.length > 0">
                    <div class="user-item user-item-active" @click="actionDetail(item.id, item)" v-for="(item, index) in tempDataList" :key="index">
                        <div class="user-picture">
                            <div class="pic" v-if="item.avatar_url">
                                <img :src="item.avatar_url" alt="">
                            </div>
                            <el-icon v-else size="26" color="#fff"><UserFilled /></el-icon>
                        </div>
                        <div class="user-msg">
                            <span class="user-name">{{item.name}}</span>
                            <span class="msg">{{$t('chat-txt.txt-2')}}: ({{item.unread_count}})</span>
                        </div>
                        <div class="time">{{ formatTime(item.last_communication_time) }}</div>
                    </div>
                </div>
                <el-empty v-else :description="$t('chat-txt.txt-3')" image=" " />
            </el-collapse-item>
            <el-collapse-item :title="`${$t('chat-txt.txt-4')} (0)`" name="2">
                <el-empty :description="$t('chat-txt.txt-5')" image=" " />
            </el-collapse-item>
            <el-collapse-item :title="`${$t('chat-txt.txt-6')} (${dataList.length})`" name="3">
                <div class="user-list" v-if="dataList.length > 0">
                    <div class="user-item" :class="item.id == selectedUserId ? 'user-item-active' : ''" @click="actionDetail(item.id, item)" v-for="(item, index) in dataList" :key="index">
                        <div class="user-picture">
                            <div class="pic" v-if="item.avatar_url">
                                <img :src="item.avatar_url" alt="">
                            </div>
                            <el-icon v-else size="26" color="#fff"><UserFilled /></el-icon>
                        </div>
                        <div class="user-msg">
                            <span class="user-name">{{item.name}}</span>
                            <span class="msg">{{$t('chat-txt.txt-2')}}: ({{item.unread_count}})</span>
                        </div>
                        <div class="time">{{ formatTime(item.last_communication_time) }}</div>
                    </div>
                </div>
                <el-empty v-else :description="$t('chat-txt.txt-7')" image=" " />
            </el-collapse-item>
        </el-collapse>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue'
import CourseService from '@/api/course'
import UserService from '@/api/user'
import { formatTime } from '@/utils/global'
const props = defineProps<{
    openChatSearch?: (e: MouseEvent) => void
    openMsgSet?: (e: MouseEvent) => void
    openAddressBook?: (e: MouseEvent) => void
    openChat?: (e: MouseEvent) => void
    isOpen?: boolean
}>()

watch(
  () => props.isOpen,
  (newVal) => {
    if(newVal) {
        // 这里可以添加打开时的逻辑
        console.log('MessageList 打开');
        if(newVal){
            getDataList();
        }
    }
  },
  { deep: true }
);

const searchKey = ref<string>('')
const msgCollapse = ref('3')
// 分页器
import type { Pagination } from '@/types/global'
const pagination = ref<Pagination>({
    page: 1,
    limit: 1000,
    total: 0,
})
// 获取最近联系人列表
const listLoading = ref(false)
const dataList = ref([])

const getDataList = () => {
    listLoading.value = true
    const searchData = {
        page: pagination.value.page,
        limit: pagination.value.limit,
    }
    CourseService.getCommunicationHistory(searchData)
        .then(res => {
            dataList.value = res.dataList || []
            pagination.value = res.pagination || pagination.value
            if(userId.value && userId.value !== null){
                let temp = dataList.value.find(item => item.id == userId.value);
                console.log(temp);
                if(temp){
                    // 之前和這個用戶有聊天記錄
                    msgCollapse.value = '3'
                    actionDetail(temp.id, temp)
                }else{
                    // 之前沒有和該用戶聊過天
                    msgCollapse.value = '1'
                    getUserInfo()
                }
                // dataList.value.map((item, index) => {
                //     if(item.id == userId.value){
                //         msgCollapse.value = '3'
                //         actionDetail(item.id, item)
                //         console.log(item);
                //     }
                // })
            }
            
        })
        .finally(() => {
            listLoading.value = false
        })
}

const selectedUserId = ref(null)
const actionDetail = (id: number, info: any) => {
    selectedUserId.value = id
    props.openChat?.(id, info)
    // console.log('打开聊天详情', id)
}




// 獲取用戶信息
const tempDataList = ref([])
const getUserInfo = () => {
    UserService.getById(userId.value)
        .then(res => {
            let tempObj = {
                id: res.id,
                avatar_url: res.avatar_url,
                name: res.last_name + res.first_name,
                unread_count: 0,
                last_communication_time: new Date().getTime()
            }
            tempDataList.value[0] = tempObj
            actionDetail(tempObj.id, tempObj)
        })
        .finally(() => {
            
        })
}
const userId = ref(null)
import { useRoute } from 'vue-router'
const route = useRoute()
onMounted(() => {
    console.log("我執行了")
    userId.value = route.query.userId ? route.query.userId : null
    console.log(userId.value)
    getDataList()
    // getUserInfo()
})
</script>

<style lang="less" scoped>
.search-set {
    padding: 4px 8px;
    background-color: #eff1f3;

    display: flex;
    align-items: center;
    flex-wrap: wrap;
    flex-shrink: 0;

    .el-input {
        margin-right: 10px;
        width: calc(100% - 26px);
        font-size: 15px;

        --el-input-border-radius: 0;
        --el-input-focus-border: #f06423;
        --el-input-focus-border-color: #f06423;
    }

    .el-icon {
        flex-shrink: 0;
        cursor: pointer;
    }

    .address-book {
        margin-top: 15px;
        width: calc(100% - 26px);
        color: #4c4c4c;
        font-size: 15px;

        display: flex;
        align-items: center;
        justify-content: flex-end;

        .cursor {
            cursor: pointer;

            display: flex;
            align-items: center;
            justify-content: flex-end;
            gap: 6px;
        }
    }
}

.collapse-box {
    flex-grow: 1;
    overflow-y: auto;
    background-color: #eff1f3;

    .el-collapse {
        --el-collapse-header-bg-color: #f7f7f7;
        --el-collapse-border-color: rgba(0, 0, 0, 0.085);
        --el-collapse-header-font-size: 15px;
        --el-collapse-header-height: 40px;

        :deep(.el-collapse-item) {
            .el-collapse-item__header {
                padding: 8px;
            }

            .el-collapse-item__wrap {
                border-top: 1px solid var(--el-collapse-border-color);

                .el-collapse-item__content {
                    padding-bottom: 0;
                }
            }
        }
    }
}

.user-list {
    .user-item {
        border-bottom: 1px solid rgba(0, 0, 0, 0.085);
        padding: 8px;
        cursor: pointer;

        display: flex;
        align-items: center;

        &:hover {
            background-color: #f8f9fa;
        }

        &:last-child {
            border: none;
        }

        .user-picture {
            border-radius: 50%;
            background-color: #e5e5e5;
            width: 38px;
            height: 38px;

            display: flex;
            align-items: center;
            justify-content: center;
        }

        .user-msg {
            padding-left: 8px;
            flex-grow: 1;
            color: #4c4c4c;
            font-size: 15px;
            line-height: 1.666;

            .user-name {
                font-weight: bold;
                display: block;
            }

            .msg {
                display: block;
            }
        }

        .time {
            font-size: 12px;
            color: #4c4c4c;
        }
    }
    .user-item-active{
        background-color: #DEE2E6;
    }
}

:deep(.el-empty) {
    --el-empty-padding: 10px 0;
    --el-empty-description-margin-top: 0;

    .el-empty__image {
        display: none;
    }
}
</style>
